const express = require("express")
const model = require("../db/model")
const router = express.Router()
router.post("/addTodo",async (req,res)=>{
    const { todoName } = req.body
    try{
        await model.create( {todoName} )
        const result = await model.find()
        res.send({success: true,msg: "创建成功", data: result})
    }catch(err){
        console.log(err)
        res.send({success: false, msg: "创建失败，请稍后再试"})
    }
    
})

router.get("/getTodos",async (req,res)=>{
    try{
        const result = await model.find()
        res.send({success: true,msg: "查询成功", data: result})
    }catch(err){
        console.log(err)
        res.send({success: false, msg: "查询失败，请稍后再试"})
    }
    
})


router.post("/updateTodo",async (req,res)=>{
    try{
        const { id,targetIsDone } = req.body
        await model.updateOne({_id:id},{$set:{isDone:targetIsDone}})
        const result = await model.find()
        res.send({success: true,msg: "单个任务状态修改成功", data: result})
    }catch(err){
        console.log(err)
        res.send({success: false, msg: "单个任务状态修改失败，请稍后再试"})
    }
})

router.post("/updateTodoName",async (req,res)=>{
    try{
        const { id,todoName } = req.body
        await model.updateOne({_id:id},{$set:{todoName:todoName}})
        const result = await model.find()
        res.send({success: true,msg: "单个任务名称修改成功", data: result})
    }catch(err){
        console.log(err)
        res.send({success: false, msg: "任务名称设置重复"})
    }
})

router.post("/updateTodos",async (req,res)=>{
    try{
        const { targetIsDone } = req.body
        await model.updateMany({},{$set:{isDone:targetIsDone}})
        const result = await model.find()
        res.send({success: true,msg: "全选操作成功", data: result})
    }catch(err){
        console.log(err)
        res.send({success: false, msg: "全选操作失败，请稍后再试"})
    }
})

router.post("/deleteTodo",async (req,res)=>{
    try{
        const { id } = req.body
        await model.deleteOne({_id:id})
        const result = await model.find()
        res.send({success: true,msg: "单个任务删除成功", data: result})
    }catch(err){
        console.log(err)
        res.send({success: false, msg: "单个任务删除失败，请稍后再试"})
    }
})

router.post("/deleteTodos",async (req,res)=>{
    try{
        await model.deleteMany({isDone: true})
        const result = await model.find()
        res.send({success: true,msg: "删除任务成功", data: result})
    }catch(err){
        console.log(err)
        res.send({success: false, msg: "删除任务失败，请稍后再试"})
    }
})
module.exports = router